package com.ruoyi.cms.service.impl;

import com.ruoyi.cms.domain.MaterialUse;
import com.ruoyi.cms.mapper.MaterialUseMapper;
import com.ruoyi.cms.service.IMaterialUseService;
import com.ruoyi.cms.util.CmsConstants;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.exception.base.BaseException;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 素材Service业务层处理
 *
 * @author wujiyue
 * @date 2019-11-05
 */
@Service
public class MaterialUseServiceImpl implements IMaterialUseService {
    @Autowired
    private MaterialUseMapper materialUseMapper;

    @Override
    public List<MaterialUse> selectMaterialUseList(MaterialUse materialUse) {
        return materialUseMapper.selectMaterialUseList(materialUse);
    }

    @Override
    @Transactional
    public void deleteMaterialUseBatch(MaterialUse materialUse) {
        String[] arr = Convert.toStrArray(materialUse.getIds());

        List<MaterialUse> materialUses = materialUseMapper.selectMaterialUseByIds(arr);
        if (CollectionUtils.isNotEmpty(materialUses)) {
            for (MaterialUse temp : materialUses) {
                if (temp.getType() == MaterialUse.Type.NOT) {
                    throw new BaseException("删除失败,该素材使用记录不允许删除");
                }
                deleteMaterialUse(temp);
            }
        }
    }

    @Override
    public void deleteMaterialUse(MaterialUse materialUse) {
        materialUseMapper.deleteMaterialUseByMx(materialUse.getMaterialId(),
                materialUse.getUseTable(), materialUse.getUseId(), materialUse.getUseColumn(),
                materialUse.getMaterialColumn());
        int n = materialUseMapper.selectCountMaterialUse(materialUse.getMaterialId());
        if (n == 0) {
            materialUseMapper.updateMaterialUseState(materialUse.getMaterialId(), CmsConstants.USE_STATE_NO);
        }
    }

    @Transactional
    @Override
    public int deleteMaterialsUseByUse(String table, String useId, String column, String materialColumn) {
        List<MaterialUse> materialUses = selectMaterialUseList(new MaterialUse(table, useId, column, materialColumn));
        if (CollectionUtils.isNotEmpty(materialUses)) {
            for (MaterialUse temp : materialUses) {
                deleteMaterialUse(temp);
            }
            return materialUses.size();
        }
        return 0;
    }

    @Override
    @Transactional
    public void insertMaterialUse(MaterialUse use) {
        materialUseMapper.insertMaterialUse(use);
        materialUseMapper.updateMaterialUseState(use.getMaterialId(), CmsConstants.USE_STATE_YES);
    }
}
